﻿using System;
using System.Text;
using chromium.Utils;

namespace chromium.Log
{
    public abstract class AbstractLogger : ILog
    {
        public void Error(string msg)
        {
            RenderLoggingEvent(new LoggingEvent(LoggingLevel.ERROR, msg));
        }

        public void Error(string msg, Exception exception)
        {
            RenderLoggingEvent(new LoggingEvent(LoggingLevel.ERROR, msg, exception));
        }

        public void InfoFormat(string format, params object[] parameters)
        {
            RenderLoggingEvent(new LoggingEvent(LoggingLevel.INFO, string.Format(format, parameters)));
        }

        public void Debug(string msg)
        {
            RenderLoggingEvent(new LoggingEvent(LoggingLevel.DEBUG, msg));
        }

        public void Debug(string msg, Exception exception)
        {
            RenderLoggingEvent(new LoggingEvent(LoggingLevel.DEBUG, msg, exception));
        }

        public void DebugFormat(string foramt, params object[] parameters)
        {
            RenderLoggingEvent(new LoggingEvent(LoggingLevel.DEBUG, string.Format(foramt, parameters)));
        }

        protected void RenderLoggingEvent(LoggingEvent loggingEvent)
        {
            if (loggingEvent.Level < Settings.LoggingLevel)
                return;
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendLine(string.Format("{0} {1}", loggingEvent.Level, loggingEvent.Msg));

            if (loggingEvent.Exception != null)
            {
                stringBuilder.AppendLine(loggingEvent.Exception.Message);
                stringBuilder.AppendLine(loggingEvent.Exception.StackTrace);
            }

            Append(stringBuilder.ToString());
        }

        protected abstract void Append(string message);
    }
}
